package com.huiminpay.merchant.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@Controller
@Api(value = "微信相关操作",tags = "微信相关操作",description = "微信相关操作")
public class WeixinContraller {
    @Autowired
    RestTemplate restTemplate;
    @GetMapping("index")
    public void index(HttpServletResponse response)  {
        //1 第一步：用户同意授权，获取code
        //
        //2 第二步：通过code换取网页授权access_token
        //
        //3 第三步：刷新access_token（如果需要）
        //
        //4 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        String appid= "wx91645d8008a10167",redirect_uri="http://2zsfqw.natappfree.cc/merchant/getCode",scope="snsapi_userinfo";
        //显示redirect_uri参数错误的话用一下的方法
        try {
            redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope="+scope+"&state=STATE#wechat_redirect";
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    @GetMapping("getCode")
    @ResponseBody
    public void getCode(String code){
        System.out.println(code);
       // 2 第二步：通过code换取网页授权access_token
        String appid= "wx91645d8008a10167",SECRET="28d2163d5a8a88bb2632113e8ff7f0d0";

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+SECRET+"&code="+code+"&grant_type=authorization_code";

        String forObject = restTemplate.getForObject(url, String.class);

        String token = JSON.parseObject(forObject).getString("access_token");
        String openId = JSON.parseObject(forObject).getString("openid");
        //4 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openId+"&lang=zh_CN";
        String forObject1 = restTemplate.getForObject(url1,String.class);
        System.out.println(forObject1);
        //业务逻辑通过openid查询数据库

    }
}
